package com.example.demo.service.impl;

import com.example.demo.model.*;
import com.example.demo.model.vo.PartsCerteriaVo;
import com.example.demo.repository.PartsRepository;
import com.example.demo.service.PartsService;
import com.example.demo.util.AllRecords;
import com.example.demo.util.Result;
import com.example.demo.util.ResultVO;
import com.querydsl.core.types.dsl.Expressions;
import jdk.nashorn.internal.ir.Assignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by zkq19 on 2018/7/1.
 */
@Service
public class PartsServiceImpl implements PartsService{

    @Autowired
    private PartsRepository partsRepository;

    @Override
    public Result<AllRecords<Parts>> queryPage(PartsCerteriaVo partsCerteriaVo) {
        com.querydsl.core.types.dsl.BooleanExpression booleanExpression = Expressions.asBoolean(true).isTrue();

        if(!StringUtils.isEmpty(partsCerteriaVo.getCode())){
            booleanExpression = booleanExpression.and(QParts.parts.code.eq(partsCerteriaVo.getCode()));
        }
        if(!StringUtils.isEmpty(partsCerteriaVo.getName())){
            booleanExpression = booleanExpression.and(QParts.parts.name.eq(partsCerteriaVo.getName()));
        }


        // 查找到数据

        Page<Parts> result = partsRepository.findAll(booleanExpression,
                new PageRequest(partsCerteriaVo.getPageIndex() - 1, partsCerteriaVo.getPageSize(), new Sort(Sort.Direction.DESC, "createTime")));
        //给确实的名称或字段赋值
        List<Parts> partsList = result.getContent();
        AllRecords<Parts> allRecords = new AllRecords();
        allRecords.setDataList(partsList);
        allRecords.setPageIndex(partsCerteriaVo.getPageIndex());
        allRecords.setPageSize(partsCerteriaVo.getPageSize());
        allRecords.setTotalNumber(result.getTotalElements());
        allRecords.setTotalPage(result.getTotalPages());
        return ResultVO.success(allRecords);
    }
}
